﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI.WebControls;
using DevExpress.Data;
using DevExpress.Data.PivotGrid;
using DevExpress.Utils;
using DevExpress.Web.ASPxPager;
using DevExpress.Web.ASPxPivotGrid;
using DevExpress.Web.ASPxTabControl;
using DevExpress.Web.Mvc;
using DevExpress.XtraPivotGrid;
using DistanceLearning.Filters;
using DistanceLearning.Models;
using WebMatrix.WebData;
using CustomFieldDataEventArgs = DevExpress.Web.ASPxPivotGrid.CustomFieldDataEventArgs;
using PivotCellValueEventArgs = DevExpress.Web.ASPxPivotGrid.PivotCellValueEventArgs;

namespace DistanceLearning.Controllers
{
    //[Authorize(Roles = JournalStatic.AdminRole)]
    //[Authorize(Roles = JournalStatic.SchoolAdminRole)]
    [Authorize(Roles = JournalStatic.CompositeRole)]
    [InitializeSimpleMembership]
    public class JournalController : JournalBaseController
    {
        public ActionResult Index()
        {
            var subjects = GetVisibleSubjects();
            ViewData["Subjects"] = subjects;
            var lessons = GetLessons(subjects.First().SubjectName);
            return View("Index", lessons);
        }

        private IQueryable<Subject> GetVisibleSubjects()
        {
            switch (UserKind)
            {
                case UserKind.Admin:
                case UserKind.SchoolAdmin:
                case UserKind.Pupil:
                case UserKind.Parent:
                    return JournalContext.Subjects;
                case UserKind.Teacher:
                    var teacher = JournalContext.Teachers.FirstOrDefault(t => t.TeacherID == WebSecurity.CurrentUserId);
                    return JournalContext.TeacherSubjects.Where(ts => ts.TeacherID == teacher.TeacherID).Select(t => t.Subject);
            }

            return null;
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult InlineEditingUpdatePartial(ConcreteLessonPupilDetails pupilDetails, string subjectName, int? rowIndex, int? columnIndex, bool? isResetGridViewPageIndex)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var record = JournalContext.ConcreteLessonPupilDetails.First(
                        pd => pd.ConcreteLessonID == pupilDetails.ConcreteLessonID && pd.PupilID == pupilDetails.PupilID);
                    // TODO: update entity
                    record.Mark1 = pupilDetails.Mark1;
                    record.Mark2 = pupilDetails.Mark2;
                    record.IsAbsent = pupilDetails.IsAbsent;
                    JournalContext.SubmitChanges();
                }
                catch (Exception e)
                {
                    ViewData["EditError"] = e.Message;
                }
            }
            else
                ViewData["EditError"] = "Пожалуйста исправьте ошибки.";

            var lessons = GetLessons(subjectName);
            object dataObject = rowIndex != null && columnIndex != null
                ? PivotGridExtension.CreateDrillDownDataSource(DrillDownPivotGridSettings, lessons, columnIndex.Value, rowIndex.Value)
                : null;
            return PartialView("GridViewPartial", dataObject);
        }

        public ActionResult JournalPagePartial(JournalGridOptions options)
        {
            var lessons = GetLessons(options.SubjectName);
            //var lessons = GetLessons();
            return PartialView("JournalPagePartial", lessons);
        }

        private IQueryable<ConcreteLessonPupilDetails> GetLessons(string subjectName)
        {
            IQueryable<Journal> visibleJournals = null;
            if (Roles.IsUserInRole(JournalStatic.AdminRole) || Roles.IsUserInRole(JournalStatic.SchoolAdminRole))
                visibleJournals = JournalContext.Journals;
            var teacher = JournalContext.Teachers.FirstOrDefault(t => t.TeacherID == WebSecurity.CurrentUserId);
            if (teacher != null)
                visibleJournals = JournalContext.JournalLessons.Where(l => l.TeacherID == teacher.TeacherID).Select(x => x.Journal).Distinct();
            var lessons = JournalContext.ConcreteLessonPupilDetails.Where(l => l.ConcreteLesson.JournalLesson.SubjectID == subjectName && visibleJournals.Any(vd => vd.JournalID == l.ConcreteLesson.JournalID));
            return lessons;
        }

        public ActionResult GridViewPartial(string subjectName, int? rowIndex, int? columnIndex, bool? isResetGridViewPageIndex)
        {
            var lessons = GetLessons(subjectName);
            object dataObject = rowIndex != null && columnIndex != null
                ? PivotGridExtension.CreateDrillDownDataSource(DrillDownPivotGridSettings, lessons, columnIndex.Value, rowIndex.Value)
                : null;

            if (isResetGridViewPageIndex != null)
                ViewBag.IsResetGridViewPageIndex = isResetGridViewPageIndex.Value;
            return PartialView("GridViewPartial", dataObject);
        }

        //public ActionResult ExportTo([Bind]PivotGridExportDemoOptions options)
        //{
        //    return PivotGridDemoHelper.ExportTypes[options.ExportType].Method(PivotGridDemoHelper.GetPivotGridExportSettings(options), NorthwindDataProvider.GetCustomerReports());
        //}

        private PivotGridSettings _drillDownPivotGridSettings;
        public PivotGridSettings DrillDownPivotGridSettings
        {
            get
            {
                if (_drillDownPivotGridSettings == null)
                    _drillDownPivotGridSettings = CreatePivotGridSettings();
                return _drillDownPivotGridSettings;
            }
        }

        public PivotGridSettings CreatePivotGridSettings()
        {
            PivotGridSettings settings = new PivotGridSettings();

            settings.Name = "journalPivotGrid";
            settings.CallbackRouteValues = new { Controller = "Journal", Action = "JournalPagePartial" };
            //settings.CustomActionRouteValues = new { Controller = "Journal", Action = "CustomActionSampleReportsPartial" };
            settings.Width = Unit.Percentage(100);
            settings.OptionsView.ShowHorizontalScrollBar = true;

            settings.CustomGroupInterval += OnCustomGroupInterval;
            settings.CustomUnboundFieldData += OnCustomUnboundFieldData;
            settings.CustomCellValue += OnCustomCellValue;
            settings.ClientSideEvents.CellClick = "OnPivotGridCellClick";
            settings.ClientSideEvents.BeginCallback = "OnJournalGridBeginCallback";
            settings.Styles.CellStyle.Cursor = "pointer";
            settings.OptionsPager.RowsPerPage = 50;


            settings.Fields.Add(field =>
            {
                field.Area = PivotArea.RowArea;
                field.AreaIndex = 0;
                field.FieldName = "Pupil.Journal.JournalName";
                field.Caption = "Класс";
                field.SummaryType = PivotSummaryType.Average;
            });
            settings.Fields.Add(field =>
            {
                field.Area = PivotArea.RowArea;
                field.AreaIndex = 1;
                //field.FieldName = "Pupil.UserDetails.LastName";
                field.UnboundExpression = "Concat([Pupil.UserDetails.LastName], ' ', [Pupil.UserDetails.FirstName], ' ', [Pupil.UserDetails.PatronymicName])";
                field.UnboundType = UnboundColumnType.String;
                field.Caption = "Имя ученика";

                //field.CellFormat.FormatType = FormatType.Custom;
            });
            settings.Fields.Add(field =>
            {
                field.Area = PivotArea.ColumnArea;
                field.AreaIndex = 0;
                field.FieldName = "ConcreteLesson.Date";
                field.Caption = "Четверть";
                field.GroupInterval = PivotGroupInterval.Custom;
                field.SummaryType = PivotSummaryType.Average;
                field.GrandTotalText = "Среднее";
            });
            settings.Fields.Add(field =>
            {
                field.Area = PivotArea.ColumnArea;
                field.AreaIndex = 1;
                field.FieldName = "ConcreteLesson.Date";
                field.Caption = "Месяц";
                field.GroupInterval = PivotGroupInterval.DateMonth;
                field.TotalsVisibility = PivotTotalsVisibility.None;
            });
            settings.Fields.Add(field =>
            {
                field.Area = PivotArea.ColumnArea;
                field.AreaIndex = 2;
                field.FieldName = "ConcreteLesson.Date";
                field.Caption = "Дата";
                field.GroupInterval = PivotGroupInterval.Date;
                field.ValueFormat.FormatType = FormatType.DateTime;
                field.ValueFormat.FormatString = "dd";
            });
            settings.Fields.Add(field =>
            {
                field.Visible = true;
                field.Area = PivotArea.DataArea;
                field.AreaIndex = 0;
                field.Caption = "Оценка";
                field.UnboundType = UnboundColumnType.Object;
                field.EmptyCellText = string.Empty;
                field.EmptyValueText = string.Empty;
                field.FieldName = "Mark1";
                field.SummaryType = PivotSummaryType.Average;
                //field.UnboundExpression
                //field.UnboundType = UnboundColumnType.String;
                field.CellFormat.FormatString = "{0:0.##}";
                field.CellFormat.FormatType = FormatType.Numeric;

            });

            //settings.PreRender = (sender, e) => {
            //    UpdatePivotGridLayout((MVCxPivotGrid)sender);
            //};
            //settings.BeforeGetCallbackResult = (sender, e) => {
            //    if (ViewBag.IsReloadLayout != null && ViewBag.IsReloadLayout)
            //        UpdatePivotGridLayout((MVCxPivotGrid)sender);
            //};

            return settings;
        }
    }

    public enum PivotGridExportFormats { Pdf, Excel, Mht, Rtf, Text, Html }

    public static class JournalGridHelper
    {
        
    }

    public class JournalGridOptions
    {
        public string SubjectName { get; set; }
    }
}
